<template>
  <view>
    <input type="flie"/>
    <view class="svg-img" :style="{'backgroundImage':`url(${svgData})`,'width':width,'height':height}"/>
  </view>

</template>

<script>

export default {
  props: {
    path: {
      type: String,
      default: '',
      require: true
    },
    color: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '20px'
    },
    height: {
      type: String,
      default: '20px'
    }
  },
  data() {
    return {
      svgData: ``
    }
  },
  async created() {
    const re = await this.getRow()
    this.svgData = re
    const res = this.svgToUrl(this.svgData)
    if (this.color) {
      this.svgData = this.changeColor(res, this.color)
    } else {
      this.svgData = res
    }
  },
  methods: {
    async getRow() {
      const res = await fetch(this.path)
      const res2 = await res.blob()
      const file = new File([res2], 'file.txt')
      //   const res3 = await this.imgbase(file)
      //   console.log(res3, 8998)
      //   this.svgData = res3
      //   console.log(this.svgData, 'dwx')
      return new Promise((resolve) => {
        var reader = new FileReader()
        reader.readAsText(file)
        reader.onload = function (e) {
          resolve(e.target.result)
        }
      })
    },

    changeColor(url, color) {
      const res = url.replace(/%23[a-zA-Z0-9]{6}/g, color.replace('#', '%23')) // 转义后的#等于%23，利用正则表达式，替换所有%23后6位为新的十六进制六位数。
      return res
    },
    svgToUrl(url) {
      var encoded = url
        .replace(/<!--(.*)-->/g, '')
        .replace(/[\r\n]/g, ' ')
        .replace(/"/g, `'`)
        .replace(/%/g, '%25')
        .replace(/&/g, '%26')
        .replace(/#/g, '%23')
        .replace(/{/g, '%7B')
        .replace(/}/g, '%7D')
        .replace(/</g, '%3C')
        .replace(/>/g, '%3E')

      const res = '"' + `data:image/svg+xml,${encoded}` + '"'// 需要在字符串前后加上一对引号（非常关键！）
      return res
    }
  }
}
</script>

<style lang="scss" scoped>
.svg-img {
  display: block;
}
</style>